package smecta.client.print.controller.product;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import smecta.client.print.domain.ScpProductPropertyValuelist;
import smecta.client.print.domain.ScpProductSpecs;
import smecta.client.print.mapper.ScpProductPropertyValuelistMapper;
import smecta.client.print.mapper.ScpProductSpecsMapper;

import java.util.HashMap;
import java.util.List;

@Component
public class SpecsController {

    @Autowired
    private ScpProductPropertyValuelistMapper propertyValuelistMapper;

    @Autowired
    private ScpProductSpecsMapper scpProductSpecsMapper;

    @FXML
    private TableView<ScpProductSpecs> table;

    @FXML
    private TableColumn<ScpProductSpecs, String> col1;

    @FXML
    private TableColumn<ScpProductSpecs, String> col2;

    @FXML
    private TableColumn<ScpProductSpecs, String> col3;

    @FXML
    private TableColumn<ScpProductSpecs, String> col4;

    public void manualInit() {
        // 初始化数据
        List<ScpProductSpecs> list = scpProductSpecsMapper.selectAll();
        // 可以添加更多数据...
        table.getItems().clear();
        table.getItems().addAll(list);
    }

    // 属性 枚举值
    private HashMap<String, ObservableList<String>> attrEnumMap = new HashMap<>();

    @FXML
    public void initialize() {
        initColumnEnum();
        table.setEditable(true); // 使表格可编辑

        col1.setCellValueFactory(new PropertyValueFactory<>("fenteshu"));
        col1.setCellFactory(ComboBoxTableCell.forTableColumn(attrEnumMap.get("fenteshu")));
        col1.setOnEditCommit(
                event -> {
                    event.getTableView().getItems().get(
                            event.getTablePosition().getRow()).setFenteshu(event.getNewValue());
                    updateCol4BasedOnCols(event.getRowValue());
                }
        );

        col2.setCellValueFactory(new PropertyValueFactory<>("fshu"));
        col2.setCellFactory(ComboBoxTableCell.forTableColumn(attrEnumMap.get("fshu")));
        col2.setOnEditCommit(
                event -> {
                    event.getTableView().getItems().get(
                            event.getTablePosition().getRow()).setFshu(event.getNewValue());
                    updateCol4BasedOnCols(event.getRowValue());
                }
        );

        col3.setCellValueFactory(new PropertyValueFactory<>("nianxiang"));
        col3.setCellFactory(ComboBoxTableCell.forTableColumn(attrEnumMap.get("nianxiang")));
        col3.setOnEditCommit(
                event -> {
                    event.getTableView().getItems().get(
                            event.getTablePosition().getRow()).setNianxiang(event.getNewValue());
                    updateCol4BasedOnCols(event.getRowValue());
                }
        );

        col4.setCellValueFactory(new PropertyValueFactory<>("guige"));
    }

    /**
     * 根据 col1、col2 和 col3 的值更新 col4。
     */
    private void updateCol4BasedOnCols(ScpProductSpecs productSpecs) {
        if (productSpecs == null) {
            return;
        }
        String value1 = productSpecs.getFenteshu();
        String value2 = productSpecs.getFshu();
        String value3 = productSpecs.getNianxiang();

        // 计算 col4 的值，这里以简单的拼接为例
        String col4Value = computeCol4Value(value1, value2, value3);
        productSpecs.setGuige(col4Value);

        // 刷新表格对应的行，以显示更新后的值
        int rowIndex = table.getItems().indexOf(productSpecs);
        if (rowIndex != -1) {
            table.refresh();
            TableColumn<ScpProductSpecs, String> currentCol = col4;
            currentCol.getCellFactory().call(col4).setText(col4Value); // 直接设置单元格文本
        }
    }

    /**
     * 计算 col4 的值。
     */
    private String computeCol4Value(String col1Value, String col2Value, String col3Value) {
        // 这里实现具体的计算逻辑，例如拼接字符串
        return String.format("%s/%s-%s",col1Value,col2Value,col3Value);
    }

    private void initColumnEnum() {
        attrEnumMap.clear();
        List<ScpProductPropertyValuelist> all = propertyValuelistMapper.selectScpProductPropertyValuelistList(new ScpProductPropertyValuelist());
        for (ScpProductPropertyValuelist item : all) {
            String key = item.getCode();
            String value = item.getValue();
            if (!attrEnumMap.containsKey(key)) {
                attrEnumMap.put(key, FXCollections.observableArrayList());
            }
            attrEnumMap.get(key).add(value);
        }
    }

    public void add() {
        table.getItems().add(new ScpProductSpecs("请选择","请选择","请选择",null));
        table.refresh(); // 刷新表格显示新数据
    }

    public void del() {
        table.getItems().remove(table.getItems().size() - 1);
        table.refresh(); // 刷新表格显示新数据
    }

    public void save() {
        List<ScpProductSpecs> all = scpProductSpecsMapper.selectAll();
        for (int i = 0; i < all.size(); i++) {
            scpProductSpecsMapper.deleteByPrimaryKey(all.get(i).getId());
        }

        table.getItems().forEach(item -> {
            List<ScpProductSpecs> query = scpProductSpecsMapper.select(item);
            if (CollectionUtils.isEmpty(query)) {
                scpProductSpecsMapper.insertSelective(item);
            }
        });
    }
}